#include <stdio.h>
#include <string.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "driver/gpio.h"
#include "bq2022a_led.h"
#include "esp_log.h"

#define LED_IO_GREEN 12
#define LED_IO_RED 14

typedef struct
{
    led_mode_t led_mode;
    uint8_t red_led_lvl;
    uint8_t green_led_lvl;
}led_t;

static led_t g_led = 
{
    .led_mode = RED_LED_ON,
    .red_led_lvl = 0,
    .green_led_lvl = 1
};

void bq2022a_led_blink(void)
{
    switch (g_led.led_mode)
    {
        case RED_LED_ON:
            g_led.green_led_lvl = 1;
            g_led.red_led_lvl = 0;
            break;
        case RED_LED_BLINK:
            g_led.green_led_lvl = 1;
            g_led.red_led_lvl = !g_led.red_led_lvl;
            break;
        case GREEN_LED_ON:
            g_led.red_led_lvl = 1;
            g_led.green_led_lvl = 0;
            break;
        case GREEN_LED_BLINK:
            g_led.red_led_lvl = 1;
            g_led.green_led_lvl = !g_led.green_led_lvl;
            break;
        default:
            break;
    }
    gpio_set_level(LED_IO_GREEN,g_led.green_led_lvl);
    gpio_set_level(LED_IO_RED,g_led.red_led_lvl);
}

static void bq2022a_led_task(void* param)
{
    for(;;)
    {
        bq2022a_led_blink();
        vTaskDelay(50 / portTICK_PERIOD_MS);
    }
}

void bq2022a_led_init(void)
{
    gpio_config_t led_io = 
    {
        .pin_bit_mask = (1<<LED_IO_GREEN)|(1<<LED_IO_RED),
        .mode = GPIO_MODE_OUTPUT,
        .pull_up_en = GPIO_PULLUP_DISABLE,
        .pull_down_en = GPIO_PULLDOWN_DISABLE,
        .intr_type = GPIO_INTR_DISABLE,
    };
    gpio_config(&led_io);
    gpio_set_level(LED_IO_GREEN,g_led.green_led_lvl);
    gpio_set_level(LED_IO_RED,g_led.red_led_lvl);
    BaseType_t err = xTaskCreate(
                         bq2022a_led_task,
                         "led_task",
                         1024,
                         NULL,
                         2,
                         NULL);
    if (err != pdTRUE) {
        ESP_LOGE("LED", "create LED task failed");
    }
}

void bq2022a_mode_set(led_mode_t mode)
{
    g_led.led_mode = mode;
}